# -*- coding: utf-8 -*-


# cmap2owl -- Helper application to convert from concept maps to OWL ontologies
# Copyright (c) 2008-2013  Rodrigo Rizzi Starr
#  
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


'''
Maps a CMap represented as an independent representation into an OWL ontology.
This is basically a KB with mapping heuristics

@author: Rodrigo Rizzi Starr
@copyright: Copyright © 2008-2013 Rodrigo Rizzi Starr
@license: MIT License
@contact: rodrigo.starr@gmail.com
'''


import sys
import traceback
import cPickle as pickle

# swi-prolog  interface
from prologWrapper import Prolog
from pyswip.prolog import PrologError

# Project imports
from log import log, statLog
from infoBox import InfoBox
from action import Action
from CMap2Prolog import CMap2Prolog
from classifiers import Classifiers
from mapperRules.compositionRule import CompositionRule
from mapperRules.unificateSimilarRule import UnificateSimilarRule
from mapperRules.generalizationRule import GeneralizationRule
from mapperRules.specializationRule import SpecializationRule
from mapperRules.conceptRules import ConceptRule
from mapperRules.relationRules import RelationRule
from mapperRules.domainRangeRule import DomainRangeRule
from mapperRules.transitivityRule import TransitivityRule
from mapperRules.disjunctionRule import DisjunctionRule
from mapperRules.enumerationRule import EnumerationRule
from mapperRules.inverseRelationRule import InverseRelationRule
from mapperRules.functionalRules import FunctionalRule
from mapperRules.allDifferentIndividualsRule import AllDifferentIndividualsRule 
from mapperRules.sufficientRule import SufficientRule
from mapperRules.adjectivePhraseRule import AdjectivePhraseRule
from mapperRules.splitDisjunctionRule import SplitDisjunctionRule

from timeFunc import print_timing, tic, toc
log.debug('Loaded...')


class Mapper:
    '''Realizes the mapping'''
   
    def __init__(self, cmap, classifierFile, tagger):
        '''heuristics is a list of mapperRule object cmap is a CMap
           representation
        '''

        self.cmap = cmap
      
        # Creates a generic prolog DB. 
        # Ensures that the basicInference has not been already loaded
        self.db = Prolog()
        try:
            list(self.db.query('conceptCM(X)'))
        except:
            self.db.consult('basicInference.pl')
      
        heuristics = [
                      UnificateSimilarRule(self.db),
                      AdjectivePhraseRule(self.db),
                      SplitDisjunctionRule(self.db),
                      CompositionRule(self.db),
                      EnumerationRule(self.db),
#                      DisjunctionRule(self.db),
#                      AllDifferentIndividualsRule(self.db),
                      TransitivityRule(self.db),
                      InverseRelationRule(self.db),
                      FunctionalRule(self.db),
                      GeneralizationRule(self.db),
                      SpecializationRule(self.db),
                      ConceptRule(self.db),
                      RelationRule(self.db),
                      DomainRangeRule(self.db),
                      SufficientRule(self.db),
                      ]
      
        self.heuristics = heuristics
        self.infoProviders = \
                [rule.getInfoProvider() for rule in self.heuristics]
        self.actionsProviders = \
                [rule.getActionsProvider() for rule in self.heuristics]
                
        self.classifiers = Classifiers(self.db, classifierFile, cmap.getData())
        self.classifiers.load()

        with open(tagger, 'rb') as f:
            self.tagger = pickle.load(f)
        for phrase in self.cmap.graph.phrases:
            phrase.tag(self.tagger)
    
    def map(self):
        '''Process the CMap representation and create a list of questions from
         them.'''
      
        # First assert the CMap into the knowledge base
        kb = CMap2Prolog(self.cmap.getData())
        kb.createKBinEngine(self.db)
      
        # Now asserts the heuristics in the KB
        self.createClassifiers()
        self.createHeuristics()
   
    @print_timing
    def getQuestions(self, progressBox = None):
        '''Returns a list of Questions that must be answered'''
        
        if progressBox != None:
            progressBox.show()
            progressBox.mainLabel = 'Processing rules'
            progressBox.secundaryLabel = ('%d rules to be processed'
                                          % len(self.heuristics))
            progressBox.setSizeHint(len(self.heuristics))
        
        
        questions = []
      
        for rule in self.heuristics:
            try:
                t = tic()
                localQuestions = rule.getQuestions()
                statLog.info('Rule %-19s generated %-3d questions in %0.6f s', 
                          rule.name, len(localQuestions), toc(t))
                questions.extend(localQuestions)
                if progressBox != None:
                    progressBox.pulse()
            except PrologError as e:
                (type, value, stack) = sys.exc_info()
                stack = traceback.extract_tb(stack)
                message = ('********      Error caused by rule %s\n' % 
                           rule.__class__.__name__)
                message += e.message + '\n'
                message += ''.join(traceback.format_list(stack)[:-2])
                log.error(message)
        
        statLog.info('Generated %d questions', len(questions))

        return questions
      
    def getRuleConstruct(self, ruleName):
        ''''Returns the construct with name ruleName'''
        return self.heuristics[ruleName]
      
    def createClassifiers(self):
        '''Create the classifiers defined for each rule'''
        for rule in self.heuristics:
            self.classifiers.useClassifiers(rule.classifiers)
        self.classifiers.fillKB()
        
    def createHeuristics(self):
        '''Asserts every rule'''
        for rule in self.heuristics:
            rule.createRule(self.cmap.graph.phrases)
    
    def getInfoBox(self, element):
        '''Returns a widget with some useful info displayed'''
        info = []
        for provider in self.infoProviders:
            info.extend(provider.getInfo(element))
            
        return InfoBox(info)
    
    def getActions(self, element):
        '''Returns a list of widgets with some actions that can be done on the
          selected element'''
          
        info = []
        for provider in self.actionsProviders:
            info.extend(provider.getActions(element))
        
        if [] == info:
            info.append(Action())
        
        return info
    
    def clearDB(self):
        '''Clears the database of all the previous content'''
        pass
    
    def loadWordnet(self):
        '''Load the wordnet database into the prolog engine'''
        db = self.db
        db.consult('wordnet/wn_vgp.pl')
        db.consult('wordnet/wn_ant.pl')
        db.consult('wordnet/wn_at.pl')
        db.consult('wordnet/wn_cls.pl')
        db.consult('wordnet/wn_cs.pl')
        db.consult('wordnet/wn_der.pl')
        db.consult('wordnet/wn_ent.pl')
        db.consult('wordnet/wn_fr.pl')
        db.consult('wordnet/wn_g.pl')
        db.consult('wordnet/wn_hyp.pl')
        db.consult('wordnet/wn_ins.pl')
        db.consult('wordnet/wn_mm.pl')
        db.consult('wordnet/wn_mp.pl')
        db.consult('wordnet/wn_ms.pl')
        db.consult('wordnet/wn_per.pl')
        db.consult('wordnet/wn_ppl.pl')
        db.consult('wordnet/wn_sa.pl')
        db.consult('wordnet/wn_sim.pl')
        db.consult('wordnet/wn_sk.pl')
        db.consult('wordnet/wn_s.pl')
        db.consult('wordnet/wn_syntax.pl')
         
